package com.gcit.seniorWish.web.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gcit.seniorWish.core.node.ZTreeNode;
import com.gcit.seniorWish.core.util.Convert;
import com.gcit.seniorWish.core.util.ToolUtil;
import com.gcit.seniorWish.web.common.persistence.dao.RoleMenuMapper;
import com.gcit.seniorWish.web.common.persistence.dao.RoleMapper;
import com.gcit.seniorWish.web.common.persistence.model.Role;
import com.gcit.seniorWish.web.common.persistence.model.RoleMenu;
import com.gcit.seniorWish.web.common.persistence.model.User;
import com.gcit.seniorWish.web.modular.system.dao.RoleDao;
import com.gcit.seniorWish.web.modular.system.service.IRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleDao roleDao;

    @Resource
    private RoleMenuMapper roleMenuMapper;


    @Override
    @Transactional
    public void setAuthority(String roleId, String ids) {
        // 删除该角色所有的权限
        roleMenuMapper.delete(Condition.create().eq("role_id",roleId));
        // 添加新的权限
        for (String id :  Convert.toStrArray(",", ids)) {
            RoleMenu relation = new RoleMenu();
            relation.setRoleId(roleId);
            relation.setMenuId(id);
            roleMenuMapper.insert(relation);
        }
    }

    /**
    * 删除角色
    * @param roleId 角色id
    * @author gaozhichang
    * @date 2018-03-14 上午 9:12
    */
    @Override
    @Transactional
    public void delRoleById(String roleId) {
        //删除角色
        this.roleMapper.deleteById(roleId);
        // 删除该角色所有的权限
        roleMenuMapper.delete(Condition.create().eq("role_id",roleId));
    }


    /**
     * 查询角色列表（返回ZTree格式）
     * @author gaozhichang
     * @date 2018-03-14 上午 9:36
     */
    @Override
    public List<ZTreeNode> listRoleTreeNode() {
        return this.roleDao.listRoleTreeNode();
    }
    
    /**
    * 根据用户id查询角色树（角色取消父子关系）
    * @param userId 用户id
    * @author gaozhichang
    * @date 2018-03-14 上午 9:19
    */
    @Override
    public List<ZTreeNode> listRoleTreeNodeByUserId(String userId){
            return this.roleDao.listRoleTreeNodeByUserId(userId);
    }

    /**
     * 根据用户id查询当前用户拥有的角色id列表
     * @param userId 用户id
     * @author gaozhichang
     * @date 2018-03-14 上午 9:51
     */
    @Override
    public List<String> listRoleId(String userId) {
        return roleDao.listRoleIdByUserId(userId);
    }
}
